package com.crowdfunding.controller;


import com.crowdfunding.entity.CrowdFunding;
import com.crowdfunding.exception.ImageUploadException;
import com.crowdfunding.feign.UploadAdvice;
import com.crowdfunding.service.ICrowdFundingService;
import com.crowdfunding.service.ICrowdfundingImageService;
import com.crowdfunding.service.IRecordCrowdFundingService;
import com.crowdfunding.util.HttpRequestUtils;
import com.crowdfunding.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoyu
 * @since 2021-07-09
 */
@RestController
@CrossOrigin
@RequestMapping(("/crowdfunding/crowdFunding"))
public class CrowdFundingController {

    @Autowired
    ICrowdFundingService crowdFundingService;


    @GetMapping("")
    @ResponseBody
    @ApiOperation("获取众筹活动列表")
    public List<CrowdFunding> getCrowdFundingList(){
        List<CrowdFunding> list=crowdFundingService.getCrowdFundingList();
        return list;
    }

    @GetMapping("/crowdFundingOne")
    @ResponseBody
    @ApiOperation("根据众筹id获取众筹详情")
    public CrowdFunding getOneCrowdFunding(String cfId){
        return crowdFundingService.getOneCrowFunding(cfId);
    }

    @PostMapping("")
    @ResponseBody
    @ApiOperation("发布一个众筹活动")
    public ResponseEntity addCrowdFunding(@RequestHeader String token, CrowdFunding crowdFunding){
        if (JwtUtils.checkToken(token)){

            try {

                //           CrowdFunding crowdFunding=new CrowdFunding();
    //           crowdFunding.setCfCreateTime(new Date());
    //           crowdFunding.setCfTotalAmount(1500.0);
    //           crowdFunding.setCfDeadline(new Date());
    //           crowdFunding.setCfName("test555");

                //根据token解析出用户名
                crowdFunding.setUsername(JwtUtils.getUserNameByJwtToken(token));
//                 System.out.println(crowdFunding.getCfName());
//                 System.err.println("OK");
                crowdFundingService.insertCrowdFunding(crowdFunding);
                return  ResponseEntity.status(HttpStatus.OK).body("众筹发布成功，请等待审核通过");
            }catch (Exception e){
                e.printStackTrace();
                return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("众筹发布失败");
            }
    }else {
            return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("身份验证失败");
        }
    }

    @PostMapping("/addIncludeImage")
    @ResponseBody
    @ApiOperation("发布一个众筹活动,图片不用先上传，直接交由后端处理,可上传多张图片，默认第一张图片为封面图片")
    public ResponseEntity addCrowdFunding2(@RequestHeader String token, CrowdFunding crowdFunding,@RequestParam ("file")MultipartFile[] files){
        if (JwtUtils.checkToken(token)){
            try {
                if (files[0].isEmpty()){
                    throw new ImageUploadException("图片为空");
                }

                //根据token解析出用户名
                crowdFunding.setUsername(JwtUtils.getUserNameByJwtToken(token));

               crowdFundingService.addCrowdFunding(crowdFunding,files);

               return  ResponseEntity.status(HttpStatus.OK).body("众筹发布成功，请等待审核通过");

            }catch (Exception e){
                e.printStackTrace();
                return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(e.getMessage());
            }
        }else {
            return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("身份验证失败");
        }
    }


    @DeleteMapping("")
    @ResponseBody
    public ResponseEntity DeleteCrowdFunding(CrowdFunding crowdFunding){
        if (crowdFundingService.selectById(crowdFunding.getCfId())!=null){
            crowdFundingService.deleteCrowFunding(crowdFunding.getCfId());
            return ResponseEntity.status(HttpStatus.OK).body("删除成功");
        }
        else
        return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("删除失败");
    }

    @PutMapping
    @ResponseBody
    @ApiOperation("更新众筹活动信息")
    public ResponseEntity UpdateCrowFunding(CrowdFunding crowdFunding){
        CrowdFunding cF= crowdFundingService.selectById(crowdFunding.getCfId());
        if (cF!=null){
            crowdFundingService.updateCrowdFunding(crowdFunding);
            return ResponseEntity.status(HttpStatus.OK).body("更新成功");
        }else {
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("更新失败");
        }
    }

    @PostMapping("/recordCrowdFunding")
    @ResponseBody
    @ApiOperation("添加筹款人记录，参与众筹项目")
    public ResponseEntity addRecordCrowdFunding(@RequestHeader String token,double cfrAmount,String cfId){
        if (JwtUtils.checkToken(token)){
        try {
            String username=JwtUtils.getUserNameByJwtToken(token);
            //更改已筹金额
            int status = crowdFundingService.addAmount(cfrAmount, cfId,username);

            if (status==1){
                return ResponseEntity.status(HttpStatus.OK).body("筹款成功");
            }else if(status==2){
                return ResponseEntity.status(HttpStatus.OK).body("筹款成功，多余金额将原路退回");
            }else {
                return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("筹款成功，多余金额将原路退回");
            }

        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("error");
        }}
        else {
            return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("身份验证失败");
        }
    }

    @PutMapping("/changeCrowdFundingStatus")
    @ResponseBody
    public ResponseEntity changeCrowdFundingStatus(String cfId,int status){
        try {
            crowdFundingService.changeCrowdFundingStatus(cfId,status);
            return ResponseEntity.status(HttpStatus.OK).body("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("修改失败");
        }
    }

    @GetMapping("/getCrowdFundingListByuserName")
    @ResponseBody
    @ApiOperation("根据用户名（token）查询该用户发起的众筹活动")
    public ResponseEntity getCrowdFundingListByuserName(@RequestHeader String token){
        if (JwtUtils.checkToken(token)){
            try {
                String username=JwtUtils.getUserNameByJwtToken(token);
                List<CrowdFunding>crowdFundingList= crowdFundingService.getCrowdFundingListByuserName(username);
                return ResponseEntity.status(HttpStatus.OK).body(crowdFundingList);
            }catch (Exception e){
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("error");
            }
        }else {
            return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("身份验证失败");
        }
    }

    @GetMapping("/getParticipateCrowdFundingListByuserName")
    @ResponseBody
    @ApiOperation("根据用户名（token）查询该用户参与的众筹活动")
    public ResponseEntity getparticipateList(@RequestHeader String token){
        if (JwtUtils.checkToken(token)){
            try {
                String username=JwtUtils.getUserNameByJwtToken(token);
                List<CrowdFunding>crowdFundingList= crowdFundingService.getparticipateList(username);
                return ResponseEntity.status(HttpStatus.OK).body(crowdFundingList);
            }catch (Exception e){
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("error");
            }
        }else {
            return  ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("身份验证失败");
        }
    }

    }


